package mbse.kluge.boardgamegui.controller;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EFactory;
import org.eclipse.emf.ecore.EPackage;
import org.moflon.boardgamegui.controller.GenericController;

import BoardGameLanguage.Board;
import BoardGameLanguage.BoardGameLanguageFactory;
import BoardGameLanguage.BoardGameLanguagePackage;
import BoardGameLanguage.Field;
import BoardGameLanguage.Figure;
import BoardGameLanguage.facade.FacadeFactory;

public class Controller extends GenericController<Board, Field, Figure> {

	public static void main(String[] args) {
		new Controller(2, 2);
	}

	public Controller(int width, int height) {
		super(width, height);
	}

	@Override
	public EPackage getEPackage() {
		return BoardGameLanguagePackage.eINSTANCE;
	}

	@Override
	public int getBoardWidth() {
		return getBoard().getWidth();
	}

	@Override
	public int getBoardHeight() {
		return getBoard().getHeight();
	}

	@Override
	public EList<Field> getFields() {
		return getBoard().getFields();
	}

	@Override
	public Figure getFigure(Field field) {
		return field.getFigure();
	}

	@Override
	public int getFieldXCoordinate(Field field) {
		return field.getColumn();
	}

	@Override
	public int getFieldYCoordinate(Field field) {
		return field.getRow();
	}

	@Override
	public EFactory getEFactory() {
		return BoardGameLanguageFactory.eINSTANCE;
	}

	@Override
	public void addFigureToField(Figure figure, Field field) {
		figure.setField(field);
		updateView();
	}

	@Override
	public List<EClass> getConcreteFigureClasses() {
		final List<EClass> result = new ArrayList<EClass>();
		final EClass figureTypeClass = BoardGameLanguagePackage.eINSTANCE
				.getFigure();
		for (final EClassifier classifier : BoardGameLanguagePackage.eINSTANCE
				.getEClassifiers()) {
			final EClass clazz = (EClass) classifier;
			if (classifier != figureTypeClass
					&& figureTypeClass.isSuperTypeOf(clazz)
					&& !clazz.isAbstract()) {
				result.add(clazz);
			}
		}
		return result;
	}

	@Override
	public Board makeNewBoard(int width, int height) {
		final Board board = BoardGameLanguageFactory.eINSTANCE.createBoard();
		board.setWidth(width);
		board.setHeight(height);
		board.initialize(FacadeFactory.eINSTANCE.createBoardGameUtils());
		return board;
	}

	@Override
	public void fieldPressed(Field field) {
		getBoard().handleFieldPressed(field);
		updateView();
	}

}
